//
//  Home.swift
//  casdon_swiftUI
//
//  Created by ww on 2025/4/14.
//
// 数据模型
import ThingSmartDeviceKit
import SwiftUI
import FlowStacks
import SDWebImageSwiftUI

struct HomeView: View {
    @EnvironmentObject var navigator: FlowNavigator<HomeStack>
    @StateObject var viewModel = HomeViewModel()
    @State private var isRefreshing = false
    
    var body: some View {
        ZStack{
            // 背景图放在底层
            VStack {
                HomeNavigationBar(viewModel: viewModel)
                ScrollView {
                    VStack{
                        BannerView(
                            bannerItems:viewModel.bannerItems,
                            onBannerTap: { banner in
                                navigator.push(.webPage(url: banner.link))
                            },
                            onBannerLongPress: { banner in
                               navigator.push(.webPage(url: banner.link))
                            }).padding(.top, 12)
                        
                        HStack {
                            Text("my deviceList".I18n)
                                .padding(.leading, 16)
                                .font(.system(size: 16))
                                .foregroundColor(AppColors.Gy1)
                            Spacer()
                            Button(action: {
                                navigator.push(.addDevice)
                            }, label: {
                                Image("add")
                                Text("add device".I18n)
                                    .padding(.trailing, 16)
                                    .font(.system(size: 14))
                                    .bold()
                                    .foregroundColor(AppColors.Brand6)
                            })
                        }.padding(.top, 12)
                        LazyVStack {
                            CollectionView(items: viewModel.itemList, content: { item in
                                ZStack {
                                    Rectangle()
                                        .fill(Color.white)
                                        .frame(height: 114)
                                        .cornerRadius(12)
                                    VStack(alignment: .leading) {
                                        if let url = URL(string: item.iconUrl) {
                                            WebImage(url: url)
                                                .resizable()
                                                .indicator(.activity)
                                                .scaledToFit()
                                                .frame(width: 40, height: 40)
                                        } else {
                                            Image(systemName: "photo")
                                                .resizable()
                                                .frame(width: 40, height: 40)
                                                .foregroundColor(.gray)
                                        }
                                        Text(item.name)
                                            .font(.system(size: 13))
                                            .foregroundColor(AppColors.Gy1)
                                            .padding(.leading, 6)
                                            .padding(.top, 5)
                                        Text(item.isOnline ? "onLine".I18n : "offLine".I18n)
                                            .font(.system(size: 12))
                                            .foregroundColor(item.isOnline ? AppColors.Success6 : AppColors.Gy3)
                                            .padding(.bottom, 10)
                                            .padding(.top, 2)
                                            .padding(.leading, 6)
                                    }
                                }
                            }
                              , onItemTap: { item in
                                // 点击事件处理
                                viewModel.go()
                            })
                            .padding(.horizontal, 12)
                            .padding(.top, 8)
                        }
                    }
                }
                .refreshable {
                        refreshData()
                    }
            }
        }.background(
            // 设置背景图，背景图只会影响 HomeNavigationBar
            Image("home_bg")
                .resizable()
                .scaledToFill()
                .edgesIgnoringSafeArea(.all) // 背景图铺满屏幕
        )
        .onAppear{
            refreshData()
        }
    }


    func refreshData() {
        viewModel.getHomeList()
        viewModel.getUserInfo()
        viewModel.getBanners()
    }
    
    struct CollectionView<Item: Identifiable, Content: View>: View {
        let items: [Item]
        let content: (Item) -> Content
        let onItemTap: (Item) -> Void  // 点击事件的闭包
        
        init(items: [Item], @ViewBuilder content: @escaping (Item) -> Content, onItemTap: @escaping (Item) -> Void) {
            self.items = items
            self.content = content
            self.onItemTap = onItemTap
        }
        
        var body: some View {
            LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 6) {
                ForEach(items) { item in
                    Button(action: {
                        onItemTap(item)  // 触发点击事件
                    }) {
                        content(item)  // 显示内容
                    }
                    .buttonStyle(PlainButtonStyle())  // 防止 Button 默认样式影响布局
                }
            }
        }
    }

    struct HomeNavigationBar: View {
        @ObservedObject var viewModel: HomeViewModel
        var body: some View {
            HStack {
                Text("晚上好，辛苦一天吃点好的吧~")
                    .foregroundColor(AppColors.Gy2)
                    .font(.system(size: 14))
                    .padding(.leading, 12)
                
                Spacer()
                
                HStack {
                    ZStack{
                        BadgeView(show: viewModel.newAlarm)
                        Button(action: {
                            viewModel.enterAlarmView()
                        }, label: {
                            Image("alarm")
                                .resizable()
                                .scaledToFit()
                                .frame(width: 24, height: 24)
                        }).padding(.trailing, 16)
                    }
                    
                    Button(action: {
                        viewModel.enterAlarmView()
                    }, label: {
                        Image("scan")
                            .resizable()
                            .scaledToFit()
                            .frame(width: 24, height: 24)
                    }).padding(.trailing, 12)
                }
            }
            .frame(height: 44)
            
        }
    }
    
    struct BadgeView: View {
        var show: Bool
        
        var body: some View {
            if show {
                Circle()
                    .fill(Color.red)  // 红色圆点
                    .frame(width: 8, height: 8)
                    .offset(x: 6, y: -9)
            }
        }
    }
}
